import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router';
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import { usePermissStore } from '@/store/permiss';
import { checkPermission, goToHomeMenu } from "@/utils/permission";
import Home from '@/layout/home.vue';
import dutyManageRoutes from './duty-manage';
import tenantManageRoutes from './tenant-manage';
import riskSecurityRoutes from './risk-security';
import dataCenterRoutes from './data-center';
import systemRoutes from './system';
import messageRoutes from './message';


NProgress.configure({ showSpinner: false })

//parentSide指向侧边连一级，parentSideItem是没有在siderbar中配置的菜单但是和默认菜单项打开的路由同处于同一个菜单项
export const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home,
        children: [
            // 值班管理
            ...dutyManageRoutes,
            // 租户管理
            ...tenantManageRoutes,
            // 风控安保管理
            ...riskSecurityRoutes,
            // 数据中心
            ...dataCenterRoutes,
            // 系统管理
            ...systemRoutes,
            // 消息中心
            ...messageRoutes,
        ],
    },
    {
        path: '/login',
        name: 'login',
        meta: {
            title: '登录',
        },
        component: () => import(/* webpackChunkName: "login" */ '../views/login/index.vue'),
    },
    {
        path: '/user-init',
        name: 'userInit',
        meta: {
            title: 'userInit',
        },
        component: () => import(/* webpackChunkName: "init" */ '../views/user-init/index.vue'),
    },
    {
        path: '/implicit',
        name: 'implicit',
        meta: {
            title: 'implicit',
        },
        component: () => import(/* webpackChunkName: "login" */ '../views/implicit/index.vue'),
    },
    {
        path: '/403',
        name: '403',
        meta: {
            title: '没有权限',
        },
        component: () => import(/* webpackChunkName: "403" */ '../views/403/index.vue'),
    },
    {
        path: '/404',
        name: '404',
        meta: {
            title: '未找到页面',
        },
        component: () => import(/* webpackChunkName: "404" */ '../views/404/index.vue'),
    },
    {
        path: "/:pathMatch(.*)*",
        redirect: "/404",
    }
];

const router = createRouter({
    history: createWebHashHistory(),
    routes,
});

const whiteList = ['/login', '/implicit']
router.beforeEach((to, from, next) => {
    NProgress.start();
    const user = JSON.parse(localStorage.getItem('ms_user'));
    const token = localStorage.getItem('token');
    const permiss = usePermissStore();
    // 非登录用户只能访问login，implicit
    // 先判断有没有登录
    if (user && token) {
        // 如果登录了再次访问登录页，重定向到首页，或者用户已经初始化信息再次到初始化页面同样重定向到首页
        if (!!user.exist) {
            if (to.path === "/user-init" || to.path === '/login') {
                next('/');
                NProgress.done();
            } else {
                // 空路径重定向进入第一个有权限的子菜单
                if (to.path === '/') {
                    next({ path: goToHomeMenu() });
                    NProgress.done();
                } else {
                    //有无权限，用户权应该在登陆成功后保存,只有子级页面权限没父级权限403
                    let matchedList = router.resolve({ path: to.path }).matched;
                    // 权限可以为单个也可以为多个，单个全对比，多个只需要存在一个即可，不同分路由下可能存在公用一个页面的情况,merge
                    let currentRoleList = matchedList.filter(v => v.meta && v.meta.permiss).map(v => { return { permiss: v.meta.permiss } });
                    let list = currentRoleList.filter(v => {
                        if (Array.isArray(v.permiss)) {
                            return permiss.key.some(i => v.permiss.includes(i));
                        } else {
                            return permiss.key.includes(v.permiss);
                        }
                    });
                    console.log(to.path, to.meta.permiss, list.length, currentRoleList.length)
                    if (to.meta.permiss && list.length !== currentRoleList.length) {
                        // 如果没有权限，则进入403
                        next('/403');
                        NProgress.done();
                    } else {
                        // 存在子级默认跳转到存在权限的第一个子页
                        let curRouteIndex = matchedList.findIndex(v => {
                            return v.path === to.path && v.children.length > 0
                                && v.children.some((i) => i.meta.permiss && checkPermission([i.meta.permiss]))
                        });
                        if (curRouteIndex > -1) {
                            let childList = matchedList[curRouteIndex].children.filter((v) =>
                                checkPermission([v.meta.permiss])
                            );
                            next({ path: childList[0].path });
                            NProgress.done();
                        } else {
                            next();
                            NProgress.done();
                        }
                    }
                }

            }
        } else {
            // 没有初始化信息禁止进入后台
            if (!whiteList.includes(to.path) && to.path !== "/user-init") {
                next('/login');
                NProgress.done();
            } else {
                next();
                NProgress.done();
            }
        }
    } else {
        if (whiteList.includes(to.path)) {
            next();
            NProgress.done();
        } else {
            next('/login')
            NProgress.done();
        }
    }
});

export default router;
